using System;
using System.Reflection;
using System.Web;
using System.Web.UI;
using System.IO;

namespace ASPNETPerformance.App_BusinessLogic.StaticPage
{
    /// <summary>
    /// Based on ScottGu's Implementation Concept
    /// http://weblogs.asp.net/scottgu/archive/2006/10/22/Tip_2F00_Trick_3A00_-Cool-UI-Templating-Technique-to-use-with-ASP.NET-AJAX-for-non_2D00_UpdatePanel-scenarios.aspx
    /// </summary>
    public class ViewManager {
        public static string RenderView( string path ) {
            return RenderView( path, null );
        }

        public static string RenderView( string path, object data ) {
            Page pageHolder = new Page();
            UserControl viewControl = ( UserControl )pageHolder.LoadControl( path );

            if ( data != null ) {
                Type viewControlType = viewControl.GetType();
                FieldInfo field = viewControlType.GetField( "Data" );

                if ( field != null ) {
                    field.SetValue( viewControl, data );
                }
                else {
                    throw new Exception( "View file: " + path + " does not have a public Data property" );
                }
            }

            pageHolder.Controls.Add( viewControl );

            StringWriter output = new StringWriter();
            HttpContext.Current.Server.Execute( pageHolder, output, false );

            return output.ToString();
        }
    }
}
